package com.tzxs.pay.main.gather;

import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.databinding.ViewDataBinding;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.tzxs.pay.BR;
import com.tzxs.pay.R;
import com.tzxs.pay.databinding.ActivitySearchResultBinding;
import com.tzxs.pay.databinding.ItemBillAuthorizationBinding;
import com.tzxs.pay.databinding.ItemBillCollectionBinding;
import com.tzxs.pay.main.base.BaseActivity;
import com.tzxs.pay.main.bill.detail.AutTncActivity;
import com.tzxs.pay.main.bill.detail.AutTradedDetailActivity;
import com.tzxs.pay.main.bill.detail.CollAndInstallDetailActivity;
import com.tzxs.pay.main.bill.model.AutOrderBean;
import com.tzxs.pay.main.bill.model.CollectionBillBean;
import com.tzxs.pay.main.bill.viewmodel.BillViewModel;
import com.tzxs.pay.util.IAdapter;
import com.tzxs.pay.util.IHolder;

import java.util.List;

public class SearchResultActivity extends BaseActivity<ActivitySearchResultBinding> implements IAdapter.ItemNavigator<Object> {


    private static final String TAG = SearchResultActivity.class.getSimpleName();
    private String orderId;//订单号
    private String startTimeStr;//开始时间
    private String endTimeStr;//结束时间
    private String noteStr;//结束时间

    private String name;//要查询的类型  普通收款  分期  预授权
    private BillViewModel model;
    private int page = 1;//默认从第一页开始

    @Override
    protected Activity getChildActivity() {
        return this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search_result;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        model = ViewModelProviders.of(this).get(BillViewModel.class);
        getIntentContent();
        dataBinding.searchResultToolbar.setNavigationOnClickListener(v -> onBackPressed());
        dataBinding.searchResultRec.setLayoutManager(new LinearLayoutManager(this));
        model.snackbarText.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                if (s != null) {
                    Toast.makeText(SearchResultActivity.this, s, Toast.LENGTH_SHORT).show();
                }
            }
        });

        dataBinding.searchResultRec.setAdapter(new IAdapter<Object, ViewDataBinding>() {
            private int mPosition = 0;

            @Override
            protected int getLayoutId(int viewType) {
                //这样直接就把布局给替换了

                return viewType;
            }

            @Override
            public int getItemViewType(int position) {
                //判断item的不同
                Log.d(TAG, "getItemViewType: position:" + mPosition);
                Log.d(TAG, "getItemViewType: getData():" + getData().size());

                if (getData().get(mPosition) instanceof AutOrderBean.DataBean) {
                    return R.layout.item_bill_authorization;
                } else {
                    return R.layout.item_bill_collection;
                }
            }

            /**
             * 设置navigator监听
             * @param binding binding
             */
            @Override
            protected void convertListener(@NonNull ViewDataBinding binding) {
                super.convertListener(binding);
                binding.setVariable(BR.itemNavigator, SearchResultActivity.this);
            }


            @Override
            public boolean areItemsTheSame(List<Object> oldData, List<Object> data, int oldItemPosition, int newItemPosition) {
                if (oldData.get(oldItemPosition) instanceof CollectionBillBean && data.get(newItemPosition) instanceof CollectionBillBean) {
                    return ((CollectionBillBean) oldData.get(oldItemPosition)).getOut_trade_no().equals(((CollectionBillBean) data.get(newItemPosition)).getOut_trade_no());
                } else if (oldData.get(oldItemPosition) instanceof AutOrderBean.DataBean && data.get(newItemPosition) instanceof AutOrderBean.DataBean) {
                    return ((AutOrderBean.DataBean) oldData.get(oldItemPosition)).getOut_order_no().equals(((AutOrderBean.DataBean) data.get(newItemPosition)).getOut_order_no());
                } else {
                    return super.areItemsTheSame(oldData, data, oldItemPosition, newItemPosition);
                }
            }

            @Override
            protected int getDataBRId(int itemViewType) {
                if (itemViewType == R.layout.item_bill_authorization) {
                    return BR.order_aut;
                } else {
                    return BR.item;
                }
            }

            @Override
            public void onBindViewHolder(IHolder<ViewDataBinding> holder, int position) {
                mPosition = holder.getAdapterPosition();
                super.onBindViewHolder(holder, position);
                //当类型为收款和分期的时候
                if (getData().get(position) instanceof CollectionBillBean && holder.binding instanceof ItemBillCollectionBinding) {
                    CollectionBillBean bean = (CollectionBillBean) getData().get(position);

                    ItemBillCollectionBinding binding = (ItemBillCollectionBinding) holder.binding;
                    if (bean.getType() == 106) {//当为分期付款时
                        binding.collectionItemNote.setVisibility(View.INVISIBLE);
                        binding.noteText.setVisibility(View.INVISIBLE);

                    } else {//其他
                        binding.collectionItemNote.setVisibility(View.INVISIBLE);
                        binding.noteText.setVisibility(View.INVISIBLE);
                    }
                    switch (bean.getPay_status()) {
                        case 1:
                            binding.collectionItemTradeState.setTextColor(Color.parseColor("#1F78CF"));
                            break;
                        case 2:
                            binding.collectionItemTradeState.setTextColor(Color.parseColor("#999999"));
                            break;
                        case 3:
                            binding.collectionItemTradeState.setTextColor(Color.parseColor("#27AA30"));
                            break;
                        case 4:
                            binding.collectionItemTradeState.setTextColor(Color.parseColor("#ED433F"));
                            break;
                        case 5:
                            binding.collectionItemTradeState.setTextColor(Color.parseColor("#EB9205"));
                            break;
                    }
                    binding.collectionItemTradeState.setText(bean.getPay_status_txt());
                    //支付方式
                    switch (bean.getPay_type()) {
                        case "weixin":

                            binding.collectionWechatIcon.setImageResource(R.drawable.ic_wechat);
                            break;
                        case "alipay":
                            binding.collectionWechatIcon.setImageResource(R.drawable.ic_alipay);
                            break;
                        default:
                            binding.collectionWechatIcon.setImageResource(R.drawable.ic_unionpay);
                            break;
                    }


                } else {
                    if (holder.binding instanceof ItemBillAuthorizationBinding) {
                        ItemBillAuthorizationBinding binding = (ItemBillAuthorizationBinding) holder.binding;

                        if (getData().get(position) instanceof AutOrderBean.DataBean) {
                            AutOrderBean.DataBean bean = (AutOrderBean.DataBean) getData().get(position);
                            String payStr = null;
                            switch (bean.getPay_status()) {
                                case 1:
                                    payStr = "等待结算";
                                    binding.autState.setTextColor(Color.parseColor("#1F78CF"));
                                    break;
                                case 2:
                                    payStr = "支付失败";
                                    binding.autState.setTextColor(Color.parseColor("#999999"));
                                    break;
                                case 3:
                                    payStr = "等待支付";
                                    binding.autState.setTextColor(Color.parseColor("#27AA30"));
                                    break;
                                case 4:
                                    payStr = "结算成功";
                                    binding.autState.setTextColor(Color.parseColor("#ED433F"));
                                    break;
                                case 5:
                                    payStr = "已退款";
                                    binding.autState.setTextColor(Color.parseColor("#EB9205"));
                                    break;
                            }
                            binding.autState.setText(payStr);
                            //支付方式
                            switch (bean.getPay_type()) {
                                case "wexin":

                                    binding.autPayIcon.setImageResource(R.drawable.ic_wechat);
                                    break;
                                case "alipay":
                                    binding.autPayIcon.setImageResource(R.drawable.ic_alipay);
                                    break;
                                default:
                                    binding.autPayIcon.setImageResource(R.drawable.ic_unionpay);
                                    break;
                            }
                        }

                    }

                }
            }
        });
        dataBinding.setViewModel(model);


        //进入页面加载数据
        switch (name) {
            case "aut":
                model.getDepositBills(false, null, page, 10,
                        orderId, noteStr, startTimeStr, endTimeStr, 0, name, () -> {


                        });

                break;
            case "install":
                model.getCoInResultBills("106", null, noteStr, -1, page, 10, orderId,
                        startTimeStr, endTimeStr, () -> {
                        });

                break;
            default: //普通收款
                //获取数据
                model.getCoInResultBills(null, "all", noteStr, -1, page, 10, orderId,
                        startTimeStr, endTimeStr, () -> {
//                        Log.d(TAG, "onCreate: 获取数据成功！");

                        });


                break;
        }

        dataBinding.refresh.setOnRefreshListener(refreshLayout -> {
            page = 1;


            switch (name) {
                case "aut":
                    model.getDepositBills(false, null, page, 10,
                            orderId, noteStr, startTimeStr, endTimeStr, 0, name, () -> {


                            });

                    refreshLayout.finishRefresh(1000);
                    break;
                case "install":
                    model.getCoInResultBills("106", null, noteStr, -1, page, 10, orderId,
                            startTimeStr, endTimeStr, () -> {
                            });

                    refreshLayout.finishRefresh(1000);
                    break;
                default:
                    //获取数据
                    model.getCoInResultBills(null, "all", noteStr, -1, page, 10, orderId,
                            startTimeStr, endTimeStr, () -> {

//                            Log.d(TAG, "onCreate: 获取数据成功！");


                            });
                    refreshLayout.finishRefresh(1000);
                    break;
            }
        });
        dataBinding.refresh.setOnLoadMoreListener(refreshLayout -> {
            ++page;
            switch (name) {
                case "aut":
                    model.getDepositBills(false, null, page, 10,
                            orderId, noteStr, startTimeStr, endTimeStr, 0, name, () -> {

                            });
                    refreshLayout.finishLoadMore(1000);
                    break;
                case "install":
                    model.getCoInResultBills("106", null, noteStr, -1, page, 10, orderId,
                            startTimeStr, endTimeStr, () -> {
                            });

                    refreshLayout.finishLoadMore(1000);
                    break;
                default:
                    model.getCoInResultBills(null, "all", noteStr, -1, page, 10, orderId,
                            startTimeStr, endTimeStr, () -> {
                            });

                    refreshLayout.finishLoadMore(1000);
                    break;
            }
        });

    }


    //从上个页面获取的搜索条件
    private void getIntentContent() {
        Intent intent = getIntent();
        orderId = intent.getStringExtra("orderId");
        name = intent.getStringExtra("name");
        startTimeStr = intent.getStringExtra("startTime");
        endTimeStr = intent.getStringExtra("endTime");
        noteStr = intent.getStringExtra("note");
    }

    /**
     * item点击事件
     *
     * @param item ItemView用到的数据
     */

    @Override
    public void itemClick(Object item) {
        if (item instanceof CollectionBillBean) {//收款获取分期的时候
            Intent intent = new Intent(this, CollAndInstallDetailActivity.class);
            intent.putExtra("orderId", ((CollectionBillBean) item).getOut_trade_no());
            startActivity(intent);

        } else {
            Intent intent;
            if (((AutOrderBean.DataBean) item).getPay_status() == 1) {
                //当订单状态为可结算的时候跳转到可结算页面
                intent = new Intent(this, AutTncActivity.class);
            } else {
                //当订单为其他状态则跳转
                intent = new Intent(this, AutTradedDetailActivity.class);

            }
            intent.putExtra("orderId", ((AutOrderBean.DataBean) item).getOut_order_no());
            startActivity(intent);
        }

    }
}
